﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using personalplaner.common.mvvm;
using personalplaner.business.stamm;
using System.Collections.ObjectModel;
using personalplaner.common.mvvm.common;
using personalplaner.servicemodel.common;
using personalplaner.servicemodel.dataaccess;
using personalplaner.common.mvvm.commands;
using System.Windows.Input;
using personalplaner.gui.common;
using personalplaner.business;
using personalplaner.gui.stamm.views;
using personalplaner.business.enums;
using personalplaner.common.mvvm.mediator;

namespace personalplaner.gui.stamm.viewmodels
{
	public class PlanStammViewModel : BaseViewModel
	{
		public PlanStammViewModel(DependencyObject parent)
			: base(parent)
		{
		}

		public override void Loaded()
		{
			var mw = GetService<IMainWindowDisplayContainer>();
			mw.IsWaitVisible = false;
		}


        /// <summary>
        /// Subscribe to the mediator to receive a message when a plan was deleted
        /// </summary>
        /// <param name="planid"></param>
        [MediatorMessageSink("PlanDeleted", ParameterType = typeof(int))]
        public void PlanDeleted(int planid)
        {
            _arbeitsplanlist = null;
            RaisePropertyChanged("Arbeitsplanlist");

            var mw = GetService<IMainWindowDisplayContainer>();
            mw.IsWaitVisible = false;
        }

		#region Commands

        #region Default

        ICommand _okcommand;
		public ICommand OkCommand
		{
			get
			{
				if (_okcommand == null)
					_okcommand = new RelayCommand(OnOkCommand);
				return _okcommand;
			}
		}

		private void OnOkCommand(object parameter)
		{
			//// use mediator to notify all suscribed methods that the list of plans has to be refreshed
			//Mediator.NotifyColleagues("RefreshPlanList");

			var wnd = Parent as Window;
			if (wnd != null)
			{
				wnd.DialogResult = true;
				wnd.Close();
				return;
			}

			var mw = GetService<IMainWindowDisplayContainer>();
			mw.MoveToPreviousView();
		}

		ICommand _cancelcommand;
		public ICommand CancelCommand
		{
			get
			{
				if (_cancelcommand == null)
					_cancelcommand = new RelayCommand(OnCancelCommand);
				return _cancelcommand;
			}
		}

		private void OnCancelCommand(object parameter)
		{
			var wnd = Parent as Window;
			if (wnd != null)
			{
				wnd.DialogResult = false;
				wnd.Close();
				return;
			}

			var mw = GetService<IMainWindowDisplayContainer>();
			mw.MoveToPreviousView();
		}

		ICommand _reactivatecommand;
		public ICommand ReactivateCommand
		{
			get
			{
				if (_reactivatecommand == null)
					_reactivatecommand = new RelayCommand(OnReactivate, param => SelectedArbeitsPlan != null && SelectedArbeitsPlan.Status == business.enums.enStatus.Inactive);
				return _reactivatecommand;
			}
		}

		private void OnReactivate(object parameter)
		{
			if (SelectedArbeitsPlan == null)
				return;

			var da = GetService<IPlanDataAccess>();
			da.UpdatePlanStatus(SelectedArbeitsPlan.PlanId, business.enums.enStatus.Active);

			SelectedArbeitsPlan.Status = business.enums.enStatus.Active;

			// use mediator to notify all suscribed methods that the list of plans has to be refreshed
			Mediator.NotifyColleagues("RefreshPlanList");

            var mw = GetService<IMainWindowDisplayContainer>();
            mw.IsWaitVisible = false;
		}

        ICommand _deactivateCommand;
        public ICommand DeactivateCommand
		{
			get
			{
                if (_deactivateCommand == null)
                    _deactivateCommand = new RelayCommand(OnDeactivate, param => SelectedArbeitsPlan != null && SelectedArbeitsPlan.Status == business.enums.enStatus.Active);
                return _deactivateCommand;
			}
		}

        private void OnDeactivate(object parameter)
		{
			if (SelectedArbeitsPlan == null)
				return;

			var da = GetService<IPlanDataAccess>();
			da.UpdatePlanStatus(SelectedArbeitsPlan.PlanId, business.enums.enStatus.Inactive);

			SelectedArbeitsPlan.Status = business.enums.enStatus.Inactive;

			// use mediator to notify all suscribed methods that the list of plans has to be refreshed
			Mediator.NotifyColleagues("RefreshPlanList");

            var mw = GetService<IMainWindowDisplayContainer>();
            mw.IsWaitVisible = false;
		}

		ICommand _savecommand;
        public ICommand SaveCommand
        {
            get
            {
                if (_savecommand == null)
					_savecommand = new RelayCommand(OnSave, p => SelectedArbeitsPlan != null && SelectedArbeitsPlan.Status == business.enums.enStatus.Active);
                return _savecommand;
            }
        }

		private void OnSave(object parameter)
		{
			if (SelectedArbeitsPlan == null)
				return;

			var da = GetService<IPlanDataAccess>();

			string tmp = da.GetPlanName(SelectedArbeitsPlan.PlanId);

			if (tmp != SelectedArbeitsPlan.Name)
			{
				da.UpdatePlanName(SelectedArbeitsPlan.PlanId, SelectedArbeitsPlan.Name);

				// use mediator to notify all suscribed methods that the list of plans has to be refreshed
				Mediator.NotifyColleagues("RefreshPlanList");
			}

            var mw = GetService<IMainWindowDisplayContainer>();
            mw.IsWaitVisible = false;
		}

        ICommand _deleteCommand;
        public ICommand DeleteCommand
        {
            get
            {
                if (_deleteCommand == null)
                    _deleteCommand = new RelayCommand(OnDelete, param => SelectedArbeitsPlan != null && SelectedArbeitsPlan.Status == business.enums.enStatus.Active);
                return _deleteCommand;
            }
        }

        private void OnDelete(object parameter)
        {
            if (MessageBox.Show(Window.GetWindow(Parent), personalplaner.gui.Properties.Resources.DeletePlanMessage, personalplaner.gui.Properties.Resources.Delete, MessageBoxButton.OKCancel, MessageBoxImage.Warning) != MessageBoxResult.OK)
                return;

            GetService<IErrorLoger>().LoggMessage(enMessageType.USER_EVENT, string.Format("Delete plan {0} clicked", SelectedArbeitsPlan.PlanId));
            var da = GetService<IPlanDataAccess>();
            da.DeletePlan(SelectedArbeitsPlan.PlanId);

            var options = GetService<IOptionsDataAccess>();
            if (options.DeleteSchemaOnDeletePlan)
            {

                var sda = GetService<IPlanSchemaDataAccess>();
                var plaene = sda.GetPlaeneFromSchemaId(SelectedArbeitsPlan.SchemaId);

                // only delete the layout if only 1 plan was created with it
                if (plaene != null && !plaene.Any())
                {
                    if (sda.DeleteSchema(SelectedArbeitsPlan.SchemaId) && options.ResetLastSchemaOnDeleteSchema)
                    {
                        var layouts = sda.GetSchemas(false);
                        if (layouts == null || !layouts.Any())
                        {
                            layouts = sda.GetSchemas(true);
                            if (layouts != null && layouts.Any())
                            {
                                // reactivate a schema
                                var schemaid = layouts.Max(l => l.SchemaID);
                                sda.UpdateSchemaStatus(schemaid, true);
                            }
                        }
                        Mediator.NotifyColleagues<int>("SchemaDeleted", SelectedArbeitsPlan.SchemaId);
                    }
                }
            }

            // use mediator to notify all suscribed methods that a plan was deleted
            Mediator.NotifyColleagues<int>("PlanDeleted", SelectedArbeitsPlan.PlanId);
        }

        #endregion

        #region Plan

        ICommand _editLayoutCommand;
        public ICommand EditLayoutCommand
        {
            get
            {
                if (_editLayoutCommand == null)
                    _editLayoutCommand = new RelayCommand(OnEditLayout, p => SelectedArbeitsPlan != null && SelectedArbeitsPlan.Status == enStatus.Active);
                return _editLayoutCommand;
            }
        }

        private void OnEditLayout(object param)
        {
            var itm = new PlanLayoutStamm();
            itm.SetSinglePlanSchema(SelectedArbeitsPlan.SchemaId);

            var service = GetService<IMainWindowDisplayContainer>();
            service.AddSimpleContentItem(enDisplayItemType.PlanLayoutStamm, itm, true);
        }

        #endregion

        #endregion

        #region Properties

        IList<ArbeitsPlanHeader> _arbeitsplanlist;
		public IList<ArbeitsPlanHeader> ArbeitsPlanList
		{
			get
			{
				if (Designer.IsDesignMode)
					return new ObservableCollection<ArbeitsPlanHeader>();

				if (_arbeitsplanlist == null)
				{
					var da = GetService<IPlanDataAccess>();
					var lst = da.GetArbeitsPlaene(false);
					_arbeitsplanlist = lst != null ? new ObservableCollection<ArbeitsPlanHeader>(lst.OrderByDescending(a => a.PlanId)) : new ObservableCollection<ArbeitsPlanHeader>();
				}
				return _arbeitsplanlist;
			}
		}

		ArbeitsPlanHeader _selectedArbeitsPlan;
		public ArbeitsPlanHeader SelectedArbeitsPlan
		{
			get { return _selectedArbeitsPlan; }
			set
			{
				_selectedArbeitsPlan = value;
				RaisePropertyChanged("SelectedArbeitsPlan");
			}
		}

		#endregion
	}
}
